﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace CarController
{
    class NetworkInterface
    {
        static Pololu servoControl;

        static void Main(string[] args)
        {
            servoControl = new Pololu("COM1");
            TcpListener UIlistener = new TcpListener(IPAddress.Any, 9091);
            UIlistener.Start();
            Console.WriteLine("Listening");
            while (true)
            {

                TcpClient UIClient = UIlistener.AcceptTcpClient();
                Console.WriteLine("Connected");
                StreamReader UIReader = new StreamReader(UIClient.GetStream());
                StreamWriter UIWriter = new StreamWriter(UIClient.GetStream());

                try
                {
                    while (!UIReader.EndOfStream)
                    {
                        string cmd = UIReader.ReadLine();

                        Console.WriteLine("COMMAND: " + cmd);

                        if (cmd.StartsWith("SPEED:"))
                        {
                            servoControl.SetSpeed(double.Parse(cmd.Split(':')[1]));
                        }
                        else if (cmd.StartsWith("STEER:"))
                        {
                            servoControl.SetSteering(double.Parse(cmd.Split(':')[1]));
                        }
                        else if (cmd.StartsWith("PAN:"))
                        {
                            servoControl.SetPan(double.Parse(cmd.Split(':')[1]));
                        }
                        else if (cmd.StartsWith("TILT:"))
                        {
                            servoControl.SetTilt(double.Parse(cmd.Split(':')[1]));
                        }
                        else if (cmd == "KILL")
                        {
                            servoControl.Kill();
                        }
                        /*else if (cmd == "HEARTBEAT")
                        {
                            lastHeartbeat = DateTime.Now;
                        }*/
                    }
                }
                catch
                {
                }
            }

        }
    }
}
